<template>
  <div class="userLayout">
    <div class="login_panel">
      <el-row>
        <el-col :xs="0">
          <img class="login_panel_left_img" src="@/assets/login_left.svg" />
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24">
          <div class="login_panel_form">
            <div class="login_panel_form_title">
              <img class="login_panel_form_title_logo" :src="config.logo" />
              <p class="login_panel_form_title_p">{{ config.appName }}</p>
            </div>
            <el-form
              ref="loginForm"
              :model="loginFormData"
              :rules="rules"
              :validate-on-rule-change="false"
              @keyup.enter="submitForm"
              v-if="!isEmail"
            >
              <el-form-item prop="account">
                <el-input
                  v-model="loginFormData.account"
                  size="large"
                  placeholder="请输入用户名"
                  prefix-icon="User"
                />
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="loginFormData.password"
                  show-password
                  size="large"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                />
              </el-form-item>
              <el-form-item>
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    margin: -8px 0 4px;
                    width: 100%;
                  "
                >
                  <el-text
                    style="cursor: pointer"
                    type="primary"
                    @click="isEmail = !isEmail"
                  >
                    邮箱登录
                  </el-text>
                  <el-text
                    style="cursor: pointer"
                    type="primary"
                    @click="registerDialog = true"
                  >
                    新用户注册
                  </el-text>
                </div>
                <el-button
                  type="primary"
                  :loading="loading"
                  size="large"
                  style="width: 100%"
                  @click="submitForm"
                >
                  登录
                </el-button>
              </el-form-item>
            </el-form>
            <el-form
              ref="loginEmailForm"
              :model="loginEmailFormData"
              :rules="emailRules"
              :validate-on-rule-change="false"
              @keyup.enter="submitFormByEmail"
              v-else
            >
              <el-form-item prop="email">
                <el-input
                  type="email"
                  v-model="loginEmailFormData.email"
                  size="large"
                  placeholder="请输入邮箱"
                  prefix-icon="User"
                />
              </el-form-item>
              <el-form-item prop="captcha">
                <el-input
                  v-model="loginEmailFormData.captcha"
                  size="large"
                  placeholder="请输入验证码"
                  prefix-icon="CircleCheck"
                >
                  <template #append>
                    <el-button
                      :disabled="countdown > 0"
                      @click="getLoginCaptcha()"
                    >
                      {{
                        countdown > 0
                          ? `${countdown}秒后重新获取`
                          : '获取验证码'
                      }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    margin: -8px 0 4px;
                    width: 100%;
                  "
                >
                  <el-text
                    style="cursor: pointer"
                    type="primary"
                    @click="isEmail = !isEmail"
                  >
                    邮箱登录
                  </el-text>
                  <el-text
                    style="cursor: pointer"
                    type="primary"
                    @click="registerDialog = true"
                  >
                    新用户注册
                  </el-text>
                </div>
                <el-button
                  type="primary"
                  :loading="loading"
                  size="large"
                  style="width: 100%"
                  @click="submitFormByEmail"
                >
                  登录
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-dialog v-model="registerDialog" title="新用户注册">
            <Register />
          </el-dialog>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'Login',
}
</script>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import config from '@/setting'
import Register from './register/index.vue'
import { reqGetLoginEmailCaptcha } from '@/api/email'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { useRoute, useRouter } from 'vue-router'

//获取el-form组件
const $router = useRouter()
const $route = useRoute()
const isEmail = ref(false)
const registerDialog = ref(false)
const countdown = ref(0)
// 验证函数
const checkAccount = (rule: any, value: any, callback: any) => {
  if (value.length < 5 || value.length > 16) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule: any, value: any, callback: any) => {
  if (value.length < 6 || value.length > 16) {
    return callback(new Error('请输入6位到16位的密码'))
  } else {
    callback()
  }
}

// 登录相关操作
let loginForm = ref()
const loginFormData = reactive({
  account: '',
  password: '',
})

let loginEmailForm = ref()
const loginEmailFormData = reactive({
  email: '',
  captcha: '',
})

const loading = ref(false)
const rules = reactive({
  account: [{ validator: checkAccount, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
})

const emailRules: any = reactive({
  email: [
    {
      required: true,
      type: 'email',
      message: '输入正确的邮箱',
      trigger: 'blur',
    },
  ],
  captcha: [
    { required: true, message: '输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '必须为六位验证码', trigger: 'blur' },
  ],
})

const userStore = useUserStore()

const getLoginCaptcha = async () => {
  await loginEmailForm.value.validateField('email')
  try {
    const { message } = await reqGetLoginEmailCaptcha(loginEmailFormData.email)
    startTimer()
    ElMessage.success(message)
  } catch (error) {
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

const startTimer = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const submitForm = async () => {
  //保证全部表单相校验通过再发请求
  await loginForm.value.validate()
  //加载效果:开始加载
  loading.value = true
  try {
    //保证登录成功
    await userStore.userLogin(loginFormData)
    //编程式导航跳转到展示数据首页
    //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
    let redirect: any = $route.query.redirect
    $router.push({ path: redirect || 'home' })
    //登录成功加载效果也消失
    loading.value = false
  } catch (error) {
    //登录失败加载效果消息
    loading.value = false
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}

const submitFormByEmail = async () => {
  //保证全部表单相校验通过再发请求
  await loginEmailForm.value.validate()
  //加载效果:开始加载
  loading.value = true
  try {
    //保证登录成功
    await userStore.userLoginByEmail(loginEmailFormData)
    //编程式导航跳转到展示数据首页
    //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
    let redirect: any = $route.query.redirect
    $router.push({ path: redirect || 'home' })
    //登录成功加载效果也消失
    loading.value = false
  } catch (error) {
    //登录失败加载效果消息
    loading.value = false
    ElMessage({
      type: 'error',
      message: (error as Error).message,
    })
  }
}
</script>

<style lang="scss" scoped>
.userLayout {
  background-image: url('@/assets/login_background.jpg');
  background-size: cover;
  width: 100%;
  height: 100%;
  position: relative;

  .login_panel {
    position: absolute;
    top: 3vh;
    left: 2vw;
    width: 96vw;
    height: 94vh;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;

    .login_panel_left_img {
      width: 100%;
      height: 100%;
    }

    .login_panel_form {
      width: 500px;
      background-color: #fff;
      padding: 40px 40px 40px 40px;
      border-radius: 10px;
      box-shadow: 2px 3px 7px rgba(0, 0, 0, 0.2);
      z-index: 100;

      .login_panel_form_title {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 30px 0;

        .login_panel_form_title_logo {
          width: 72px;
          height: 72px;
        }

        .login_panel_form_title_p {
          font-size: 40px;
          padding-left: 20px;
        }
      }
    }
  }
}

//小屏幕不显示右侧，将登录框居中
@media (max-width: 750px) {
  .login_panel_right {
    display: none;
  }

  .login_panel {
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
  }

  .login_panel_form {
    width: 100%;
  }
}

/*
  powerBy : bypanghu@163.com
*/
</style>
